from xmindparser import xmind_to_dict
import unicodedata
from io import StringIO
import json

string_io = StringIO()


class ReadXmind:

    def __init__(self, path, sheet='all'):
        """
        读取xmind并转换数据
        :param path: xmind文件路径
        :param sheet: 画布
        """
        self.xmind = xmind_to_dict(path)
        self.sheet = sheet

    def processed_data(self):
        """
        直接获取处理后数据
        :return:
        """
        result = []
        # 循环取每个画布数据
        for case_info in self.xmind:
            # 判断是否取全部还是指定画布数据
            if self.sheet == 'all' or self.sheet == case_info['title']:
                canvas = case_info['topic']['topics']
            else:
                continue
            # 开始利用递归函数取数据
            for case in canvas:
                if 'topics' in case.keys():
                    temporary_data = {}
                    model_name = self.deal_with_a_colon(case["title"]).split(':')
                    temporary_data[model_name[0]] = model_name[1]
                    result.append(self.loop_through_data(case['topics'], temporary_data))
        string_io.write(json.dumps(result))

    def loop_through_data(self, data: list, temporary_data: dict):
        """
        循环处理数据
        :param temporary_data: temporary_data
        :param data: topics
        :return:
        """
        for i in data:
            if i["title"] == '结果':
                temporary_data['结果'] = {}
                for the_results_of in i["topics"]:
                    results = self.deal_with_a_colon(the_results_of["title"]).split(':')
                    temporary_data['结果'][results[0]] = results[1]

            if ':' in self.deal_with_a_colon(i["title"]):
                model_name = self.deal_with_a_colon(i["title"]).split(':')
                temporary_data[model_name[0]] = model_name[1]
                self.loop_through_data(i['topics'], temporary_data)

            if i["title"] == '步骤':
                temporary_data['步骤'] = {}
                temporary_data['步骤']['step'] = []
                temporary_data['步骤']['data'] = {}
                for step in i["topics"]:
                    temporary_data['步骤']['step'].append(step['title'])
                    if 'topics' in step.keys() and step['title'] != '结果':
                        temporary_data['步骤']['data'][step['title']] = {}
                        for data_type in step['topics']:
                            if '值' in data_type["title"]:
                                temporary_data['步骤']['data'][step['title']]['值'] = self.deal_with_a_colon(
                                    data_type["title"])[2:].split(',')
                            elif '长度' in data_type["title"]:
                                data_type_value = self.deal_with_a_colon(data_type["title"]).split(':')
                                temporary_data['步骤']['data'][step['title']][
                                    data_type_value[0]] = {"value": data_type_value[1].split(','),
                                                           "err_tip": self.error_tip(data_type)}
                            elif '操作类型' in data_type["title"]:
                                data_type_value = self.deal_with_a_colon(data_type["title"]).split(':')
                                temporary_data['步骤']['data'][step['title']][data_type_value[0]] = data_type_value[1]
                            else:
                                data_type_value = self.deal_with_a_colon(data_type["title"]).split(':')
                                temporary_data['步骤']['data'][step['title']][data_type_value[0]] = {
                                    "value": data_type_value[1], "err_tip": self.error_tip(data_type)}
            """查询"""
            if i["title"] == '关系':
                temporary_data['关系'] = {}
                for relation in i["topics"]:
                    temporary_data['关系'][relation['title']] = []
                    for condition in relation['topics']:
                        temporary_data['关系'][relation['title']].append(condition['title'])
            if i["title"] == '字段':
                temporary_data['字段'] = []
                for relation in i["topics"]:
                    temporary_data['字段'].append(relation['title'])
            """删除"""
            if i["title"] == '需求':
                temporary_data['需求'] = {}
                for demand in i["topics"]:
                    demand_key_value = self.deal_with_a_colon(demand["title"]).split(':')
                    temporary_data['需求'][demand_key_value[0]] = demand_key_value[1]

            """单独处理步骤里没有操作类型的数据"""
            if i["title"] == '标签：无操作类型':
                temporary_data['步骤'] = []
                for no_step_data in i['topics'][0]['topics'][0]['topics'][0]['topics']:
                    temporary_data['步骤'].append(no_step_data['title'])
        return temporary_data

    @staticmethod
    def error_tip(data: dict):
        if 'topics' in data.keys():
            return data['topics'][0]['title']
        return None

    @staticmethod
    def deal_with_a_colon(data):
        """处理中文符合"""
        result = unicodedata.normalize('NFKC', data)
        return result


if __name__ == '__main__':
    test = ReadXmind(path=r'C:\Users\admin\Desktop\NAVS.xmind', sheet='画布2')
    test.processed_data()
    print(json.dumps(json.loads(string_io.getvalue()), ensure_ascii=False))
